from odoo import models, api


class SaleOrder(models.Model):
    _inherit = 'sale.order'

    @api.model
    def _name_search(self, name, domain=None, operator='ilike', limit=None, order=None):

        if self._context.get('search_type', '') == 'rma':
            product_id = self._context.get('product_id', None)
            if product_id:
                product_id = self.env['mrp.workorder'].browse(product_id)
                if product_id:
                    sale_order_line_ids = self.env['sale.order.line'].sudo().search([
                        ('product_id', '=', product_id.id),
                        ('qty_delivered', '>', 0),
                        ('state', 'in', ('sale', 'done'))
                    ])

                    return self._search(domain=[('id', 'in', sale_order_line_ids.mapped('order_id').ids)], limit=limit, order=order)

        return super()._name_search(name, domain, operator, limit, order)